<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称或路径或ID"
          clearable
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="handleCreate()" v-hasPermi="['cms:channel:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="primary" plain @click="handleBatchCreate()" v-hasPermi="['cms:channel:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 批量创建
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column prop="name" label="名称" width="360" />
      <el-table-column prop="path" label="访问路径" width="200" />
      <el-table-column prop="modelId" label="栏目模型" width="150">
        <template #default="{ row }">
          <span>{{ channelModelFormat(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contentModelId" label="内容模型" width="150">
        <template #default="{ row }">
          <span>{{ contentModelFormat(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="sort" label="排序" width="100" />

      <el-table-column label="操作" align="center" class-name="fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row.id)"
            v-hasPermi="['cms:channel:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleRuleUpdate(scope.row.id)"
            v-hasPermi="['cms:channel:update']"
          >
            {{ t('cms.menu.channelRuleUpdate') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cms:channel:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <!-- 添加或修改栏目对话框 -->
  <channel-form
    ref="formRef"
    v-model="dialogVisible"
    :bean-id="channelId"
    :parent="parent"
    @finished="fetchData"
  />
  <!-- 采集配置 -->
  <Dialog v-model="ruleDialogVisible" title="采集配置">
    <el-form :model="channelRule" ref="channelRulFormRef" label-width="140px" :inline="true">
      <el-row>
        <el-col>
          <el-form-item label="来源状态设置">
            <el-checkbox-group :min="1" v-model="channelRule.contentSourceStatuses" class="ml-4">
              <el-checkbox
                :key="index"
                :label="dict.value"
                :value="dict.value"
                :checked="channelRule.contentSourceStatuses.includes(dict.value)"
                size="large"
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.CMS_CHANNEL_RULE_CONTENT_STATUS
                )"
                >{{ dict.label }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="来源栏目">
            <el-button type="primary" @click="addSourceChannel()">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(item, index) in channelRule.sourceChannels" :key="index">
        <el-col>
          <el-select
            class="m-2 sourceSite"
            size="large"
            placeholder="来源站点"
            @change="fetchChannelList(index)"
            v-model="channelRule.sourceChannels[index].sourceSiteId"
          >
            <el-option
              v-for="site in siteList"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
          <el-tree-select
            :data="targetChannelList"
            v-model="channelRule.sourceChannels[index].sourceId"
            node-key="id"
            :props="{ label: 'name', disabled: 'disabled' }"
            :render-after-expand="false"
            check-strictly
            clearable
            placeholder="来源栏目"
            class="!w-240px"
            size="large"
          />
          <el-button :icon="Delete" circle @click="deleteSourceChannel(index)" />
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="channelRule.contentCreateTimeBegin"
              type="date"
              placeholder="来源文档创建时间晚于"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="channelRule.contentCreateTimeEnd"
              type="date"
              placeholder="来源文档创建时间早于"
              size="large"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="模糊匹配的标题">
            <el-button type="primary" @click="addTitle()">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(item, index) in channelRule.titles" :key="index">
        <el-col :span="10">
          <el-input
            class="w-30 m-2 matchTitle"
            size="large"
            placeholder="标题"
            v-model="channelRule.titles[index]"
            maxlength="100"
            @change="changeTitle(index, item)"
          />
          <el-button :icon="Delete" circle @click="deleteTitle(index)" />
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="采集方式">
            <el-radio-group v-model="channelRule.collectionType" class="ml-4">
              <el-radio
                :key="index"
                :label="dict.value"
                size="large"
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CMS_CHANNEL_RULE_COLL_TYPE)"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="采集后状态设置">
            <el-radio-group v-model="channelRule.contentStatus" class="ml-4">
              <el-radio
                :key="index"
                :label="dict.value"
                size="large"
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.CMS_CHANNEL_RULE_CONTENT_STATUS
                )"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="是否启用">
            <el-radio-group v-model="channelRule.status" class="ml-4">
              <el-radio
                :key="index"
                :label="dict.value"
                size="large"
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CMS_STATUS_TYPE)"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 操作按钮 -->
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton
        type="primary"
        :title="t('action.save')"
        :loading="actionLoading"
        @click="handleRuleSubmit()"
      />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="ruleDialogVisible = false" />
    </template>
  </Dialog>
  <!-- 批量创建栏目对话框 -->
  <ChannelBatchCreateForm ref="batchCreateFormRef" @success="getList" />

</template>
<script setup lang="ts" name="Channel">
import { handleTree } from '@/utils/tree'
import * as ChannelApi from '@/api/cms/channel'
import ChannelForm from '../manager/ChannelForm.vue'
import ChannelBatchCreateForm from '../manager/ChannelBatchCreateForm.vue'
import { getModelList } from '@/api/cms/model/index'
import { listSimpleSiteApi } from '@/api/cms/site/index'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { Delete } from '@element-plus/icons-vue'
import { ChannelRuleTargetVO } from '@/api/cms/channel/types'
import { SiteSimpleVO } from '@/api/cms/site/types'
import { toTree } from '@/utils/cmstree'
import type { FormInstance } from 'element-plus'
import { getSiteHeader } from '@/utils/cmscommon'
const message = useMessage() // 消息弹窗
const channelRulFormRef = ref<FormInstance>() // 栏目规则表单 Ref
const { t } = useI18n() // 国际化
// 列表相关的变量

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  name: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态

// 弹窗相关的变量
const dialogVisible = ref(false) // 是否显示弹出层
const parentOptions = ref() // 树形结构
const channelModelList = ref<any[]>([])
const contentModelList = ref<any[]>([])
const fetchChannelModelList = async () => {
  channelModelList.value = await getModelList(1)
}
const fetchContentModelList = async () => {
  contentModelList.value = await getModelList(2)
}
const fetchSiteList = async () => {
  siteList.value = await listSimpleSiteApi()
}

const fetchChannelList = async (index: number) => {
  const siteId = channelRule.value.sourceChannels[index].sourceSiteId
  targetChannelList.value = []
  if (siteId) {
    channelRule.value.sourceChannels[index].sourceId = undefined
    fetchTargetChannel(siteId)
  } else {
    targetChannelList.value = []
  }
}
const fetchTargetChannel = async (siteId: number) => {
  const treeChannels = toTree(await ChannelApi.listSimpleChannelApi(siteId))
  targetChannelList.value = []
  targetChannelList.value.push(...treeChannels)
}

// 获取下拉框[上级]的数据
const getTree = async () => {
  parentOptions.value = []
  const res = await ChannelApi.listSimpleChannelApi()
  let channel: Tree = { id: 0, name: '顶级栏目', children: [] }
  channel.children = handleTree(res)
  parentOptions.value.push(channel)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ChannelApi.getChannelListApi(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const dialogTitle = ref('edit') // 弹出层标题
const actionType = ref('') // 操作按钮的类型
// 新增操作
const handleCreate = async () => {
  setDialogTile('create')
  channelId.value = undefined
  //TODO 暂时新增没考虑新增下级
  parent.value = null
}
// 设置标题
const setDialogTile = (type: string) => {
  dialogTitle.value = t('action.' + type)
  actionType.value = type
  dialogVisible.value = true
}
// 修改操作
const handleUpdate = async (rowId: number) => {
  setDialogTile('update')
  channelId.value = rowId
  parent.value = null
  dialogVisible.value = true
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ChannelApi.recycleChannelApi(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// ========== 新增/修改 ==========
const channelId = ref<number>()
const parent = ref<any>()

const fetchData = async () => {
  dialogVisible.value = false
  actionLoading.value = false
  await getTree()
  await getList()
}

const contentModelFormat = (row) => {
  if (!row || !row.contentModelId) {
    return '未设置'
  }
  for (const model of contentModelList.value) {
    if (row.contentModelId === model.id) {
      return model.name
    }
  }
  return '未知【' + row.contentModelId + '】'
}
const channelModelFormat = (row) => {
  if (!row || !row.modelId) {
    return '未设置'
  }
  for (const model of channelModelList.value) {
    if (row.modelId === model.id) {
      return model.name
    }
  }
  return '未知【' + row.modelId + '】'
}

//规则配置
const ruleDialogVisible = ref(false) // 是否显示弹出层
const channelRule = ref({
  contentSourceStatuses: [1],
  contentCreateTimeBegin: undefined,
  contentCreateTimeEnd: undefined,
  titles: [''],
  sourceChannels: Array<ChannelRuleTargetVO>(),
  channelId: 0,
  collectionType: 1,
  contentStatus: 1,
  status: 1
})
const channelDefRule = ref({
  contentSourceStatuses: [1],
  contentCreateTimeBegin: undefined,
  contentCreateTimeEnd: undefined,
  titles: [''],
  sourceChannels: Array<ChannelRuleTargetVO>(),
  channelId: 0,
  collectionType: 1,
  contentStatus: 1,
  status: 1
})
const targetChannelList = ref([])
const siteList = ref(Array<SiteSimpleVO>())
const actionLoading = ref(false) // 按钮 Loading
//规则操作
const handleRuleUpdate = async (rowId: number) => {
  //重新赋值栏目规则配置数据
  const rule = await ChannelApi.getChannelRuleApi(rowId)
  //栏目有配置规则才赋予channelRule 否则替换默认值，显示有问题
  if (rule != null && Object.keys(rule).length > 0) {
    channelRule.value = rule
  } else {
    //未配置的栏目 用默认值代替
    channelRule.value = channelDefRule.value
  }
  channelId.value = rowId
  channelRule.value.channelId = rowId

  ruleDialogVisible.value = true
}

// 提交按钮
const handleRuleSubmit = async () => {
  const elForm = unref(channelRulFormRef)
  if (!elForm) return
  elForm.validate(async (valid) => {
    if (valid) {
      actionLoading.value = true
      // 提交请求
      try {
        await ChannelApi.updateChannelRuleApi(channelRule.value)
        message.success(t('common.updateSuccess'))
        ruleDialogVisible.value = false
      } finally {
        actionLoading.value = false
        await getList()
      }
    }
  })
}
const addTitle = () => {
  channelRule.value.titles.push('')
}
// 删除标题
const deleteTitle = (index) => {
  channelRule.value.titles.splice(index, 1)
}
const changeTitle = (index, title) => {
  channelRule.value.titles.splice(index, 1, title)
}

const addSourceChannel = () => {
  channelRule.value.sourceChannels.push({
    sourceSiteId: undefined,
    sourceId: undefined
  })
}
// 删除栏目选择
const deleteSourceChannel = (index) => {
  channelRule.value.sourceChannels.splice(index, 1)
}
/** 批量创建栏目操作 */
const batchCreateFormRef = ref()
const handleBatchCreate = () => {
  batchCreateFormRef.value.open()
}
// ========== 初始化 ==========
onMounted(async () => {
  await getTree()
  await getList()
  await fetchChannelModelList()
  await fetchContentModelList()
  await fetchSiteList()
  await fetchTargetChannel(getSiteHeader())
})
</script>
<style lang="scss">
.el-row {
  margin-bottom: 10px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.el-col-10,
.sourceSite {
  width: 240px;
  margin-left: 100px;
}

.matchTitle {
  width: 80%;
}
</style>
